package com.leyou.cart.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.cart.entity.Cart;
import com.leyou.cart.interceptors.UserInterceptor;
import com.leyou.cart.service.IcartService;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class cartServiceImpl implements IcartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "ly:cart:user:key:";

    @Override
    public void addCart(Cart cart) {
        Long id = UserHolder.getUser().getId();
        String key = KEY_PREFIX + (id.longValue());
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(key);
        addCartInRedis(cart, ops);
    }

    private void addCartInRedis(Cart cart, BoundHashOperations<String, String, String> ops) {
        String hasKey = cart.getSkuId().toString();
        Boolean boo = ops.hasKey(hasKey);
        int num = cart.getNum();
        if (null != boo && boo) {
            cart = JsonUtils.nativeRead(ops.get(hasKey).toString(), new TypeReference<Cart>() {
            });
            cart.setNum(num + cart.getNum());
        }
        ops.put(hasKey, JsonUtils.toString(cart));
    }

    @Override
    public List<Cart> queryCartList() {
        Long id = UserHolder.getUser().getId();
        String key = KEY_PREFIX + (id.longValue());
        Boolean boo = redisTemplate.hasKey(key);
        if (null == boo && !boo) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(key);
        Long size = ops.size();
        if (null == size && size < 0) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        List<String> carts = ops.values();
        return carts.stream().map(json -> JsonUtils.nativeRead(json, new TypeReference<Cart>() {
        })).collect(Collectors.toList());
    }

    @Override
    public void updateNum(Long skuId, Integer num) {
        Long id = UserHolder.getUser().getId();
        String key = KEY_PREFIX + (id.longValue());

        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(key);
        String haskey = skuId.toString();
        Long size = ops.size();
        if (null == size && size < 0) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        Cart cart = JsonUtils.nativeRead(ops.get(haskey), new TypeReference<Cart>() {
        });
        cart.setNum(num);

        ops.put(haskey, JsonUtils.toString(cart));
    }

    @Override
    public void deleteCart(String skuId) {
        Long id = UserHolder.getUser().getId();
        String key = KEY_PREFIX + (id.longValue());
        redisTemplate.opsForHash().delete(key,skuId);

    }

    @Override
    public void addCartList(List<Cart> carts) {
        Long id = UserHolder.getUser().getId();
        String key = KEY_PREFIX + (id.longValue());

        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(key);
        for (Cart cart : carts) {
            addCartInRedis(cart,ops);
        }
    }

    public void deleteCartList(Map<Long,List<Long>> idsMap){
        for (Map.Entry<Long, List<Long>> longListEntry : idsMap.entrySet()) {
            Long userId = longListEntry.getKey();
            List<Long> skuIds = longListEntry.getValue();
            for (Long skuId : skuIds) {
                String key = KEY_PREFIX + (userId.longValue());
                redisTemplate.opsForHash().delete(key,skuId.toString());
            }
        }
    }


}
